package com.dlc.shop.groupbuy.common.listener;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.bo.ProductBO;
import com.dlc.shop.bean.enums.ProdType;
import com.dlc.shop.bean.event.EsProductEvent;
import com.dlc.shop.bean.model.Sku;
import com.dlc.shop.bean.order.EsProductOrder;
import com.dlc.shop.groupbuy.common.dao.GroupActivityMapper;
import com.dlc.shop.groupbuy.common.dao.GroupSkuMapper;
import com.dlc.shop.groupbuy.common.model.GroupActivity;
import com.dlc.shop.groupbuy.common.model.GroupSku;
import com.dlc.shop.service.SkuService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 获取es商品团购数据事件
 * @author yami
 */
@Component("groupBuyEsProductListener")
@Slf4j
@AllArgsConstructor
public class EsProductListener {

    private final GroupActivityMapper groupActivityMapper;

    private final GroupSkuMapper groupSkuMapper;

    private final SkuService skuService;


    @EventListener(EsProductEvent.class)
    @Order(EsProductOrder.GROUP_BUY)
    public void groupBuyEsProductListener(EsProductEvent event) {
        List<ProductBO> productList = event.getProductList();
        if (CollUtil.isEmpty(productList) || Objects.nonNull(event.getOperationType())) {
            return;
        }
        List<ProductBO> groupBuyProductList = new ArrayList<>();
        List<Long> groupActivityIds = new ArrayList<>();
        List<Long> prodIds = new ArrayList<>();
        for (ProductBO productBO : productList) {
            if (!Objects.equals(productBO.getProdType(), ProdType.PROD_TYPE_GROUP.value())) {
                continue;
            }
            groupBuyProductList.add(productBO);
            groupActivityIds.add(productBO.getActivityId());
            prodIds.add(productBO.getProdId());
        }
        if (CollUtil.isEmpty(groupActivityIds)) {
            return;
        }
        // 获取已启用的团购商品信息
        List<GroupActivity> groupActivities = groupActivityMapper.selectList(new LambdaQueryWrapper<GroupActivity>()
                .in( GroupActivity::getGroupActivityId, groupActivityIds)
                .eq(GroupActivity::getStatus, 1)
        );

        List<GroupSku> skuList = groupSkuMapper.listSkuByProdIds(prodIds);
        Map<Long, List<GroupSku>> skuMap = skuList.stream().collect(Collectors.groupingBy(GroupSku::getProdId));
        Map<Long, GroupActivity> groupActivityMap = groupActivities.stream().collect(Collectors.toMap(GroupActivity::getGroupActivityId, g -> g));
        // 获取商品最低价
        Long currentTime = System.currentTimeMillis();
        for (ProductBO productBO : groupBuyProductList) {
            if (!groupActivityMap.containsKey(productBO.getActivityId())) {
                continue;
            }
            GroupActivity groupActivity = groupActivityMap.get(productBO.getActivityId());
            // 活动未启用，或当前时间大于等于活动结束时间， 则不添加活动信息
            if (groupActivity.getEndTime().getTime() <= currentTime) {
                continue;
            }
            // 团购商品最低价和对应sku原价
            productBO.setActivityPrice(groupActivity.getPrice());
            Long skuId = groupSkuMapper.getSkuIdByProdIdAndActPrice(productBO.getActivityId(), groupActivity.getPrice());
            Sku skuBySkuId = skuService.getSkuBySkuId(skuId);
            productBO.setActivityOriginalPrice(skuBySkuId.getOriPrice());
            productBO.setPrice(skuBySkuId.getPrice());
            productBO.setOriPrice(skuBySkuId.getOriPrice());
            long startTime = groupActivity.getStartTime().getTime();
            // 活动没有预热且活动开始时间大于当前时间，插入活动开始时间
            if (Objects.equals(groupActivity.getIsPreheat(), 0) && startTime > currentTime) {
                productBO.setActivityStartTime(startTime);
                continue;
            }
            // 活动预热、活动开始时间等于小于当前时间，插入当前时间
            productBO.setActivityStartTime(currentTime);
        }
    }

    private Double getActivityOriginalPrice(Double price, List<GroupSku> skus, Long groupActivityId) {
        if (CollUtil.isEmpty(skus)) {
            // 防止空指针-正常情况下不会出现这种情况
            log.error("id为{}的团购活动，sku列表无法获取", groupActivityId);
            return price;
        }
        // 活动sku金额正序 -> sku原价正序
        skus.sort(Comparator.comparing(GroupSku::getActPrice).thenComparing(GroupSku::getPrice));
        // 排序后，第一个sku就是活动sku金额及sku金额最低的
        return skus.get(0).getPrice();
    }


}
